<?php

namespace App\Listeners;

use App\Events\UserRecord;
use App\Models\PointRecord;
use App\Models\User;
use App\Models\UserInfo;
use DB;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class UserPointsListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserRecord  $event
     * @return void
     */
    public function handle(UserRecord $event)
    {
        $data = $event->data;
        $user = User::getWithInfoById($data['user_id']);

        if (empty($user)) {
            return;
        }

        // 自己返点0
        if ($user->info->level->self_tip == 0) {
            info("自己返点0");
            return;
        }

        // 算分
        $point = ceil($data['money'] * $user->info->level->self_tip / 1000);
        // info([
        //     'money' => $data['money'],
        //     'tip'   => $user->info->level->self_tip,
        //     'point' => $point,
        // ]);

        // 给自己加分
        $point_data = [
            'user_id'   => $data['user_id'],
            'points'    => $point,
            'type'      => PointRecord::POINT_INC,
            'from_user' => 0,
            'extends'   => [
                'level'    => $user->info->levels,
                'self_tip' => $user->info->level->self_tip,
                'money'    => $data['money'],
            ],
        ];

        DB::transaction(function () use ($point_data) {
            // 插入积分记录表
            PointRecord::create($point_data);
            // 用户加分
            UserInfo::where('user_id', $point_data['user_id'])
                ->increment('points',
                    $point_data['points']);
        });
    }
}
